package com.star.logging;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.PatternLayout;
import ch.qos.logback.classic.spi.LoggingEvent;
import ch.qos.logback.core.UnsynchronizedAppenderBase;
import com.alibaba.fastjson.JSON;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

/**
 * 飞书日志附加器
 *
 * @author tanyapeng
 * @date 2021/11/24
 */
public class LogFeiShuAppender extends UnsynchronizedAppenderBase<LoggingEvent> {
    /**
     * 默认的输出格式, %ex{12}:可以通过后面的数字指定异常栈输出的行数
     */
    private String pattern = "%level\n%m\n%logger\n%ex";
    private PatternLayout layout;
    private String profilesActive = "unknown";
    private Level nowLevel = Level.ERROR;

    private String feiShuToken;

    /**
     * 排除的类集合用逗号分隔
     */
    private String excludeThrowableClasses;

    @Override
    protected void append(LoggingEvent loggingEvent) {
        try {
            if(loggingEvent.getLevel().isGreaterOrEqual(nowLevel)) {
                if(excludeThrowableClasses != null && loggingEvent.getThrowableProxy() != null){
                    if(excludeThrowableClasses.contains(loggingEvent.getThrowableProxy().getClassName())){
                        return;
                    }
                }
                String logMsg = layout.doLayout(loggingEvent);
                sendFeiShu("https://open.feishu.cn/open-apis/bot/v2/hook/" + getFeiShuToken(), logMsg);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void start() {
        PatternLayout patternLayout = new PatternLayout();
        patternLayout.setContext(context);
        patternLayout.setPattern(getPattern());
        patternLayout.start();
        this.layout = patternLayout;
        super.start();
    }

    /**
     * 发送飞书
     * @param webHookToken
     * @param logMsg
     * @throws Exception
     */
    private void sendFeiShu(String webHookToken, String logMsg) throws Exception {
        String textMsg="{\"msg_type\": \"text\",\"content\": {\"text\": " + JSON.toJSONString(logMsg) + "}}";
        try(CloseableHttpClient httpclient = HttpClients.createDefault()) {
            HttpPost httppost = new HttpPost(webHookToken);
            httppost.addHeader("Content-Type", "application/json; charset=utf-8");
            StringEntity se = new StringEntity(textMsg, "utf-8");
            httppost.setEntity(se);
            httpclient.execute(httppost);
        } catch (Exception e) {
            throw e;
        }
    }

    public void setPattern(String pattern) {
        this.pattern = pattern;
    }

    public String getPattern() {
        return pattern;
    }

    public String getProfilesActive() {
        return profilesActive;
    }

    public void setProfilesActive(String profilesActive) {
        this.profilesActive = profilesActive;
    }

    public PatternLayout getLayout() {
        return layout;
    }

    public void setLayout(PatternLayout layout) {
        this.layout = layout;
    }

    public void setLevel(String level) {
        this.nowLevel = Level.toLevel(level, Level.ERROR);
    }

    public void setExcludeThrowableClasses(String excludeThrowableClasses) {
        this.excludeThrowableClasses = excludeThrowableClasses;
    }

    public String getFeiShuToken() {
        return feiShuToken;
    }

    public void setFeiShuToken(String feiShuToken) {
        this.feiShuToken = feiShuToken;
    }

}
